<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }"><span class="tW">首页</span></el-breadcrumb-item>
      <el-breadcrumb-item><span class="tW">用户管理</span> </el-breadcrumb-item>
      <el-breadcrumb-item><span class="tW">用户列表</span></el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索区域  :gutter 指定格与格的距离-->
      <el-row :gutter="20">
        <!--  :span 指定宽度 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUserList">
            <el-button slot="append" @click="getUserList" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">分配账号</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column prop="id" label="ID" header-align="center"></el-table-column>
        <el-table-column prop="username" label="姓名" header-align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" header-align="center"></el-table-column>
        <el-table-column prop="mobile" label="电话" header-align="center"></el-table-column>
        <el-table-column label="操作" header-align="center">
          <template slot-scope="scope">
            <!-- 修改按钮  -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页添加 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
        <!-- layout 指定功能组件 -->
      </el-pagination>
      <!-- 添加用户 对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" @close="addDialogClosed" width="50%">
        <!-- 内容主体区域 -->
        <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="100px">
          <el-form-item label="用户名ID" prop="id">
            <el-input v-model="addUserForm.id" clearable></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addUserForm.password" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" clearable></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserForm.mobile" clearable></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户 对话框 -->
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="ID">
            <el-input v-model="editForm.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import bookShareManagerInfoAipService from '@/network/aipBookShareService.js'
export default {
  data() {
    //  自定义校验 邮箱和手机号
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
      if (regEmail.test(value)) {
        // 为 true 就是合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱！'))
    }
    var checkMobile = (rule, value, cb) => {
      const regMobail = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobail.test(value)) {
        // 为 true 就是合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的电话号码！'))
    }
    var validateUserId = (rule, value, callback) => {
      let str = /^[a-zA-Z][a-zA-Z0-9]/.test(value)
      if (value === '') {
        callback(new Error('请输入用户ID'))
      } else if (value.length <= 1 || value.length >= 13) {
        callback(new Error('用户ID长度必须在 6 到 12 之间'))
      } else if (!str) {
        callback(new Error('用户ID必须以字母开头,只能包含大写和数字'))
      } else {
        callback()
      }
    }
    var validateUserName = (rule, value, callback) => {
      let str = /^[^\u4e00-\u9fa5]+$/.test(value)
      if (value === '') {
        callback(new Error('请输入用户名称'))
      } else if (value.length <= 1 || value.length >= 20) {
        callback(new Error('用户名称长度必须在 1 到 20 个字符之间'))
      } else if (!str) {
        callback(new Error('用户名称不含有中文'))
      } else {
        callback()
      }
    }
    return {
      // 用户状态
      openStatus: true,
      closeStatus: false,
      // 获取用户列表的参数对象
      queryParams: {
        query: '' // 搜索关键字
      },
      // 保存用户列表数据
      userList: [],
      total: 0,
      // 添加用户对话框的 显示与隐藏
      addDialogVisible: false,
      // 添加用户表单数据对象
      addUserForm: {
        id: '',
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 用户表单规则对象
      addUserRules: {
        id: [{ required: true, validator: validateUserId, trigger: 'blur' }],
        username: [{ required: true, validator: validateUserName, trigger: 'blur' }],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '请输入6~15个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [{ required: true, validator: checkMobile, trigger: 'blur' }]
      },
      // 修改用户对话框的 显示与隐藏
      editDialogVisible: false,
      // 保存 根据id查询的 用户信息
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      // 修改用户规则对象
      editFormRules: {
        username: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 8,
            message: '请输入1~8个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入用户邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入电话号码',
            trigger: 'blur'
          },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      },
      // 当前用户信息
      userInfo: {},
      // 所有角色数据列表
      rolesList: [],
      // 保存已选定 的 角色
      selectedRolesId: '',
      // 分页参数
      offset: 0,
      pageSize: 10, // 每页显示多少条数据
      pageNum: 1 // 当前页数
    }
  },
  created() {
    // 当页面被创建出来，获取用户列表数据
    this.getUserList(this.offset, this.pageSize, this.pageNum)
  },
  methods: {
    // 获取用户分页列表
    getUserList(offset, pageSize, pageNum) {
      bookShareManagerInfoAipService.getUserListInfo(offset, pageSize, pageNum).then(res => {
        if (res.data.code === 0) {
          this.userList = res.data.rows
          this.total = res.data.total
        } else {
          this.$message({
            showClose: true,
            message: '用户列表获取失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    // 监听 pagesize 改变事件
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getUserList(this.offset, pageSize, this.pageNum)
    },
    // 监听 页码值 改变事件
    handleCurrentChange(pageNum) {
      // offset + 10
      if (this.pageNum < pageNum) {
        this.offset += 10
        this.pageNum = pageNum
        this.getUserList(this.offset, this.pageSize, pageNum)
        return
      }
      // offset 不变
      if (this.pageNum == pageNum) {
        this.pageNum = pageNum
        this.getUserList(this.offset, this.pageSize, pageNum)
        return
      }
      // offset - 10
      if (this.pageNum > pageNum) {
        this.offset -= 10
        this.pageNum = pageNum
        this.getUserList(this.offset, this.pageSize, pageNum)
        return
      }
    },
    // 对话框关闭事件
    addDialogClosed() {
      this.$refs.addUserRef.resetFields()
    },
    // 添加用户
    addUser() {
      // 表单的预校验  和  发送网络请求
      this.$refs.addUserRef.validate(async valid => {
        console.log(valid)
        if (!valid) return
        let params = {
          userId: this.addUserForm.id,
          username: this.addUserForm.username,
          password: this.addUserForm.password,
          email: this.addUserForm.email,
          mobile: this.addUserForm.mobile,
          repassword: this.registerForm.password,
          realName: this.registerForm.username
        }
        // 发送网络请求 和 刷新用户列表信息
        bookShareManagerInfoAipService.adminRegisterInfo(params).then(res => {
          console.log(res, '分配用户')
          if (res.data.code === 0) {
            this.$message({
              showClose: true,
              message: '恭喜您，分配用户成功！',
              type: 'success',
              duration: 4000
            })
          } else {
            this.$message({
              showClose: true,
              message: '抱歉，分配用户失败！',
              type: 'error',
              duration: 4000
            })
          }
        })
        // 隐藏 弹出框
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 修改用户
    showEditDialog(id) {
      bookShareManagerInfoAipService.getUserListInfo().then(res => {
        if (res.data.code === 0) {
          res.data.rows.map(item => {
            if (id === item.id) {
              // 保存用户信息 和 显示弹出框
              this.editForm = {
                id: item.id,
                username: item.username,
                email: item.email,
                mobile: item.mobile
              }
              this.editDialogVisible = true
            }
          })
        } else {
          this.$message({
            showClose: true,
            message: '获取信息失败，请联系管理员！',
            type: 'error',
            duration: 4000
          })
        }
      })
    },
    // 修改表单 重置操作
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改表单的预验证
    editUserInfo() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return
        // 预校验成功
        console.log(this.editForm, '修改表单的预验证')
        bookShareManagerInfoAipService.editUserInfo(this.editForm).then(res => {
          if (res.data.code === 0) {
            // 更新用户信息列表
            this.getUserList()
            this.$message({
              showClose: true,
              message: '更新用户信息成功！',
              type: 'success',
              duration: 4000
            })
            // 关闭对话框
            this.editDialogVisible = false
          } else {
            this.$message({
              showClose: true,
              message: '更新用户信息失败，请联系管理员！',
              type: 'error',
              duration: 4000
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.15) !important;
}
.el-table,
.el-pagination {
  margin-top: 15px;
}
</style>
